<template>
  <div>

    <div style="display: flex; align-items: center; padding: 10px; color: #fff;">
      <span style="margin-right: 20px; font-weight: bold;">精细化天气预报</span>
      <span style="margin-right: 20px;">|</span>
      <span style="display: flex; align-items: center;">
        <span>24小时预报</span>
      </span>
    </div>

    
    <div v-if="county === '雅安'" style="margin: 20px; display: flex;">
      <el-select
        v-model="region"
        placeholder="请选择区域"
        @change="setTabs"
        style="width: 200px;"
      >
        <el-option
          v-for="option in regionOptions"
          :key="option.value"
          :label="option.label"
          :value="option.value"
        ></el-option>
      </el-select>
    </div>

  
    <el-menu
      v-if="tabs.length > 0"
      :default-active="activeTab"
      class="el-submenu-demo"
      mode="horizontal"
      @select="handleTabSelect"
    >
      <el-menu-item
        v-for="tab in tabs"
        :key="tab.name"
        :index="tab.name"
      >
        {{ tab.label }}
      </el-menu-item>
    </el-menu>
    <div class="forecast-time">预报时间: {{ forecastTime }}</div>

  
    <div id="chart" class="chart-container"></div>
  </div>
</template>

<script>
import Cookies from 'js-cookie';
import * as echarts from 'echarts';
import Request from "@/utils/request";
import { getList } from "@/views/home/refined_weather/24hTownList.js";
export default {
  data() {
    return {
      county: Cookies.get('county'),
      station_user:Cookies.get('station_user'),
      region: "雨城", 
      activeTab: "", 
      activeTabLabel: "",
      forecastTime: "",
      regionOptions: [
        { value: "雨城", label: "雨城区" },
        { value: "名山", label: "名山区" },
        { value: "天全", label: "天全县" },
        { value: "芦山", label: "芦山县" },
        { value: "宝兴", label: "宝兴县" },
        { value: "荥经", label: "荥经县" },
        { value: "汉源", label: "汉源县" },
        { value: "石棉", label: "石棉县" },
      ],
      tabs: [], 
    };
  },
  methods: {
    getForecastTime() {
      const today = new Date();
      today.setHours(13, 0, 0, 0); 
      const year = today.getFullYear();
      const month = String(today.getMonth() + 1).padStart(2, "0");
      const day = String(today.getDate()).padStart(2, "0");
      const hours = String(today.getHours()).padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:00`;
    },

    setTabs() {
      if (this.region === '雨城') {
        this.tabs = [
          { label: '雨城', name: '1' },
          { label: '上里镇', name: '2' },
          { label: '碧峰峡镇', name: '3' },
          { label: '望鱼镇', name: '4' },
          { label: '周公山镇', name: '5' },
          { label: '草坝镇', name: '6' },
          { label: '多营镇', name: '7' },
          { label: '八步镇', name: '8' },
          { label: '晏场镇', name: '9' },
          { label: '大兴街道', name: '10' },
          { label: '东城街道', name: '11' },
          { label: '西城街道', name: '12' },
          { label: '河北街道', name: '13' },
          { label: '青江街道', name: '14' }
        ];
      } else if (this.region === '名山') {
        this.tabs = [
          { label: '名山', name: '1' },
          { label: '蒙阳街道', name: '2' },
          { label: '永兴街道', name: '3' },
          { label: '万古镇', name: '4' },
          { label: '百丈镇', name: '5' },
          { label: '茅河镇', name: '6' },
          { label: '马岭镇', name: '7' },
          { label: '红星镇', name: '8' },
          { label: '新店镇', name: '9' },
          { label: '前进镇', name: '10' },
          { label: '中峰镇', name: '11' },
          { label: '蒙顶山镇', name: '12' },
          { label: '黑竹镇', name: '13' },
          { label: '车岭镇', name: '14' }
        ];
      } else if (this.region === '天全') {
        this.tabs = [
          { label: '天全', name: '1' },
          { label: '始阳镇', name: '2' },
          { label: '思经镇', name: '3' },
          { label: '喇叭河镇', name: '4' },
          { label: '仁义镇', name: '5' },
          { label: '小河镇', name: '6' },
          { label: '新场镇', name: '7' },
          { label: '城厢镇', name: '8' },
          { label: '乐英镇', name: '9' },
          { label: '新华镇', name: '10' },
          { label: '兴业乡', name: '11' }
        ];
      } else if (this.region === '芦山') {
        this.tabs = [
          { label: '芦山', name: '1' },
          { label: '芦阳街道', name: '2' },
          { label: '大川镇', name: '3' },
          { label: '飞仙关镇', name: '4' },
          { label: '双石镇', name: '5' },
          { label: '太平镇', name: '6' },
          { label: '宝盛乡', name: '7' },
          { label: '龙门乡', name: '8' },
          { label: '思延乡', name: '9' }
        ];
      } else if (this.region === '宝兴') {
        this.tabs = [
          { label: '宝兴', name: '1' },
          { label: '陇东镇', name: '2' },
          { label: '穆坪镇', name: '3' },
          { label: '灵关镇', name: '4' },
          { label: '五龙镇', name: '5' },
          { label: '大溪镇', name: '6' },
          { label: '蜂桶寨乡', name: '7' },
          { label: '硗碛藏族乡', name: '8' }
        ];
      } else if (this.region === '荥经') {
        this.tabs = [
          { label: '荥经', name: '1' },
          { label: '严道街道', name: '2' },
          { label: '花滩镇', name: '3' },
          { label: '青龙镇', name: '4' },
          { label: '荥河镇', name: '5' },
          { label: '新添镇', name: '6' },
          { label: '牛背山镇', name: '7' },
          { label: '五宪镇', name: '8' },
          { label: '龙苍沟镇', name: '9' },
          { label: '宝峰彝族乡', name: '10' },
          { label: '民建彝族乡', name: '11' },
          { label: '安靖乡', name: '12' },
          { label: '泗坪乡', name: '13' }
        ];
      } else if (this.region === '汉源') {
        this.tabs = [
          { label: '汉源', name: '1' },
          { label: '大树镇', name: '2' },
          { label: '安乐镇', name: '3' },
          { label: '九襄镇', name: '4' },
          { label: '前域镇', name: '5' },
          { label: '富庄镇', name: '6' },
          { label: '宜东镇', name: '7' },
          { label: '唐家镇', name: '8' },
          { label: '乌斯河镇', name: '9' },
          { label: '皇木镇', name: '10' },
          { label: '富林镇', name: '11' },
          { label: '清溪镇', name: '12' },
          { label: '富泉镇', name: '13' },
          { label: '富乡乡', name: '14' },
          { label: '马烈乡', name: '15' },
          { label: '河南乡', name: '16' },
          { label: '晒经乡', name: '17' },
          { label: '小堡藏族彝族乡', name: '18' },
          { label: '坭美彝族乡', name: '19' },
          { label: '永利彝族乡', name: '20' },
          { label: '顺河彝族乡', name: '21' },
          { label: '片马彝族乡', name: '22' }
        ];
      } else if (this.region === '石棉') {
        this.tabs = [
          { label: '石棉', name: '1' },
          { label: '新棉街道', name: '2' },
          { label: '安顺场镇', name: '3' },
          { label: '回隆镇', name: '4' },
          { label: '美罗镇', name: '5' },
          { label: '王岗坪彝族藏族乡', name: '6' },
          { label: '永和乡', name: '7' },
          { label: '迎政乡', name: '8' },
          { label: '丰乐乡', name: '9' },
          { label: '蟹螺藏族乡', name: '10' },
          { label: '新民藏族彝族乡', name: '11' },
          { label: '草科藏族乡', name: '12' },
          { label: '栗子坪彝族乡', name: '13' }
        ];
      }else {
        this.tabs = []; 
    }
    if (this.tabs.length > 0) {
        this.activeTab = this.tabs[0].name;
        this.activeTabLabel = this.tabs[0].label;
      }
  },
  handleTabSelect(tabName) {
  this.activeTab = tabName;
  this.activeTabLabel = this.tabs.find((tab) => tab.name === tabName).label;
  this.fetchWeatherData(tabName); 
},
fetchWeatherData(tabName) {
  if (!tabName) return; 

  const selectedTab = this.tabs.find(tab => tab.name === tabName);
  if (!selectedTab) {
    return;
  }

  Request.get("/weatherforecast/weatherforecast24H", {
    params: { town: selectedTab.label }, 
  })
    .then((response) => {
      const data = response.data.data;
      this.weatherData = data;
      this.temperatures = data.temperature;
      this.rainfall = data.rainfall; 
      this.updateChart(); 
    })
    .catch((error) => {
      console.error("天气数据请求失败:", error);
    });
},


    initChart() {
      const chartDom = document.getElementById("chart");
      this.myChart = echarts.init(chartDom);
      this.updateChart(); 
    },

    
    updateChart() {
      if (!this.weatherData) return;
      
      const option = {
        grid: {
        left: '5%',      
        containLabel: true 
        },
        backgroundColor: '#0c2340',
        tooltip: {
          trigger: "axis",
        },
        legend: {
          data: ["气温（°C）", "降水量（mm）"],
          bottom: "5%",
          textStyle: {
          color: '#fff' 
            }
        },
        xAxis: {
          type: "category",
          data: this.weatherData.date,
          axisLine: { lineStyle: { color: '#aaa' } },
          axisLabel: { color: '#fff' },
        },
        yAxis: [
          {
            type: "value",
            name: "气温（°C）",
            nameTextStyle: {
              color: "#fff", 
            },
            position: "left",
            axisLabel: {
            formatter: '{value} °C'
          },
          axisLabel: { color: '#fff' },
          axisLine: { lineStyle: { color: '#aaa' } },
          splitLine: { lineStyle: { color: '#444' } },
          },
          {
            type: "value",
            name: "降水量（mm）",
            nameTextStyle: {
              color: "#fff", 
            },
            position: "right",
            axisLabel: {
              formatter: "{value} mm",
            },
          },
        ],
        series: [
          {
            name: "气温（°C）",
            type: "line",
            data: this.temperatures,
            smooth: true, 
            lineStyle: { color: '#ffae57' }, 
            itemStyle: { color: '#ffae57' },
          },
          {
            name: "降水量（mm）",
            type: "bar",
            data: this.rainfall,
            itemStyle: {
              color: "#1f78b4",
            },
          },
        ],
      };

      this.myChart.setOption(option);
    },

    
    resizeChart() {
      if (this.myChart) {
        this.myChart.resize();
      }
    },
  },
  mounted() {
  if (this.county && this.station_user) {
    const list = getList(this.county); 
    this.tabs = list; 
  };
  this.setTabs(); 
  this.initChart(); 
  this.forecastTime = this.getForecastTime();
  if (this.tabs.length > 0) {
    this.activeTab = this.tabs[0].name; 
    this.fetchWeatherData(this.activeTab); 
  };
 
  window.addEventListener("resize", this.resizeChart); 
  
},
  beforeDestroy() {
    window.removeEventListener("resize", this.resizeChart);
  },
  
};
</script>

<style scoped>
.chart-container {
  width: 90%;
  height: 500px;
  margin-top: 20px;
}
.el-submenu-demo {
  background-color: transparent; 
  color: white;
  font-weight: bold;
}

.el-submenu-demo .el-menu-item {
  color: white; 
  border-bottom: 2px solid transparent;
  transition: all 0.3s ease;
}

.el-submenu-demo .el-menu-item:hover {
  color: #1f78b4; 
  border-bottom: 2px solid #1f78b4; 
  background-color: transparent;
}

.el-submenu-demo .el-menu-item.is-active {
  color: #1f78b4;
  border-bottom: 2px solid #1f78b4; 
  background-color: transparent;
}
</style>
